package hbec.kettle.etl.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import hbec.kettle.etl.common.constants.Constants;
import hbec.kettle.etl.common.exception.ExceptionTracker;

public class PropertiesUtils {
	private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);
	
	private static Properties engineProperties = null;
	private static Properties dbcpProperties = null;
	
	public static Properties getEngineProperties(){
		if(engineProperties == null){
			synchronized(PropertiesUtils.class){
				if(engineProperties == null){
					initialize("engine", Constants.ENGINECONF);
				}
			}
		}
		return engineProperties;
	}
	
	public static Properties getDbcpProperties(){
		if(dbcpProperties == null){
			synchronized(PropertiesUtils.class){
				if(dbcpProperties == null){
					initialize("dbcp", Constants.DBCPCONF);
				}
			}
		}
		return dbcpProperties;
	}

	private static void initialize(String conf, String path) {
		File file = new File(Constants.APP_LOCATION.concat(path));	
		if(file.exists()) {
			try {
				FileInputStream fis = new FileInputStream(file);
				switch(conf) {
					case "engine":
						engineProperties = new Properties();
						engineProperties.load(fis);
						break;
					case "dbcp":
						dbcpProperties = new Properties();
						dbcpProperties.load(fis);
						break;
					default:
						break;
				}
				fis.close();
			} catch (IOException e) {
				logger.error(ExceptionTracker.trace(e));
			}
		} else {
			try {
				Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(path);
				
				while(urls.hasMoreElements()) {
					URL url = urls.nextElement();
					if ("jar".equals(url.getProtocol())) {
						JarFile jar = ((JarURLConnection) url.openConnection()).getJarFile();
						Enumeration<JarEntry> entries = jar.entries();
						while (entries.hasMoreElements()) {
							JarEntry entry = entries.nextElement();
							if (entry.getName().equals(path)) {
								switch(conf) {
									case "engine":
										engineProperties = new Properties();
										engineProperties.load(jar.getInputStream(entry));
										break;
									case "dbcp":
										dbcpProperties = new Properties();
										dbcpProperties.load(jar.getInputStream(entry));
										break;
									default:
										break;
								}
							}
						}
					}
				}
			} catch (IOException e) {
				logger.error(ExceptionTracker.trace(e));
			}
		}
	}
}
